package com.holyn.guofang.viewcommon.tab;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.holyn.guofang.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Holyn on 2017/7/20.
 */

public class TopTabRecyclerView extends RecyclerView{

    private List<TabItem> tabItemList = new ArrayList<>();
    private MyRecyclerAdapter recyclerAdapter;

    private OnItemSelectListener onItemSelectListener;

    private LinearLayoutManager linearLayoutManager;

    /**
     * 目标项是否在最后一个可见项之后
     */
    private boolean mShouldScroll;
    /**
     * 记录目标项位置
     */
    private int mToPosition;

    public void setOnItemSelectListener(OnItemSelectListener onItemSelectListener) {
        this.onItemSelectListener = onItemSelectListener;
    }

    public interface OnItemSelectListener{
        public void OnItemSelect(int position);
    }

    public TopTabRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setBackgroundColor(ContextCompat.getColor(getContext(), R.color.white));

        recyclerAdapter = new MyRecyclerAdapter(tabItemList);
        recyclerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                smoothMoveToPosition(i);
            }
        });

        addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mShouldScroll) {
                    mShouldScroll = false;
                    smoothMoveToPosition(mToPosition);
                }
            }
        });

        setAdapter(recyclerAdapter);
        linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        setLayoutManager(linearLayoutManager);
        addItemDecoration(new MyDivider(getContext()));

    }

    /**
     * 滑动到指定位置
     *
     * @param position
     */
    public void smoothMoveToPosition(int position) {
        if (position < 0){
            position = 0;
        } else if (position > recyclerAdapter.getItemCount()){
            position = recyclerAdapter.getItemCount();
        }

        // 第一个可见位置
        int firstItem = getChildLayoutPosition(getChildAt(0));
        // 最后一个可见位置
        int lastItem = getChildLayoutPosition(getChildAt(getChildCount() - 1));

        if (position < firstItem) {
            // 如果跳转位置在第一个可见位置之前，就smoothScrollToPosition可以直接跳转
            smoothScrollToPosition(position);

            TabItem tabItem = tabItemList.get(position);

            resetDataChecek(position);


        } else if (position <= lastItem) {
            // 跳转位置在第一个可见项之后，最后一个可见项之前
            // smoothScrollToPosition根本不会动，此时调用smoothScrollBy来滑动到指定位置
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < getChildCount()) {
//                int top = getChildAt(movePosition).getTop();
//                smoothScrollBy(0, top);
                int left = getChildAt(movePosition).getLeft();
                smoothScrollBy(left, 0);
            }
            resetDataChecek(position);

        } else {
            // 如果要跳转的位置在最后可见项之后，则先调用smoothScrollToPosition将要跳转的位置滚动到可见位置
            // 再通过onScrollStateChanged控制再次调用smoothMoveToPosition，执行上一个判断中的方法
            smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }

    public void AddNewData(String item, int checkIndex){
        tabItemList.add(new TabItem(false, item));
        tabItemList.get(checkIndex).setIsCheck(true);
        recyclerAdapter.notifyDataSetChanged();
    }

    public void AddNewAllData(List<String> itemList, int checkIndex){
        for (String item : itemList){
            tabItemList.add(new TabItem(false, item));
        }
        tabItemList.get(checkIndex).setIsCheck(true);
        recyclerAdapter.notifyDataSetChanged();
    }

    public void setData(List<String> itemList, int checkIndex){
        tabItemList.clear();
        AddNewAllData(itemList, checkIndex);
    }

    private void resetDataChecek(int position){
        TabItem tabItem = tabItemList.get(position);
        if (!tabItem.getIsCheck()){
            for (TabItem item : tabItemList){
                item.setIsCheck(false);
            }
            tabItem.setIsCheck(true);
            recyclerAdapter.notifyDataSetChanged();
            onItemSelectListener.OnItemSelect(position);
        }
    }

    private class MyRecyclerAdapter extends BaseQuickAdapter<TabItem, BaseViewHolder>{

        public MyRecyclerAdapter(@Nullable List<TabItem> data) {
            super(R.layout.item_top_tab, data);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, TabItem tabItem) {
            baseViewHolder.setText(R.id.tv_value, tabItem.getValue());
            TextView tvNav = baseViewHolder.getView(R.id.tv_nav);
            if (tabItem.getIsCheck()){
                baseViewHolder.setTextColor(R.id.tv_value, ContextCompat.getColor(getContext(), R.color.blue1));
                tvNav.setVisibility(View.VISIBLE);
            } else {
                baseViewHolder.setTextColor(R.id.tv_value, ContextCompat.getColor(getContext(), R.color.black));
                tvNav.setVisibility(View.INVISIBLE);
            }
        }
    }

    private class TabItem{
        private boolean isCheck;
        private String value;

        public TabItem(boolean isCheck, String value) {
            this.isCheck = isCheck;
            this.value = value;
        }

        public boolean getIsCheck() {
            return isCheck;
        }

        public void setIsCheck(boolean check) {
            isCheck = check;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }

    private class MyDivider extends ItemDecoration{

        private Paint mPaint;
        private Drawable mDivider;

        private int mDividerWidth = 2;
        private int marginTop = 10;
        private int marginBottom = 10;

        private int mOrientation = LinearLayoutManager.HORIZONTAL;//0
        private final int[] ATTRS = new int[]{android.R.attr.listDivider};

        public MyDivider(Context context) {
            TypedArray a = context.obtainStyledAttributes(ATTRS);
            this.mDivider = a.getDrawable(0);
            a.recycle();
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            drawVerticalLine(c, parent, state);
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.set(0, 0, mDividerWidth, 0);
        }

        //画横线, 这里的parent其实是显示在屏幕显示的这部分
        public void drawHorizontalLine(Canvas c, RecyclerView parent, RecyclerView.State state){
            int left = parent.getPaddingLeft();
            int right = parent.getWidth() - parent.getPaddingRight();
            final int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++){
                final View child = parent.getChildAt(i);

                //获得child的布局信息
                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)child.getLayoutParams();
                final int top = child.getBottom() + params.bottomMargin;
                final int bottom = top + mDivider.getIntrinsicHeight();
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }

        //画竖线
        public void drawVerticalLine(Canvas c, RecyclerView parent, RecyclerView.State state){
            int top = parent.getPaddingTop() + marginTop;
            int bottom = parent.getHeight() - parent.getPaddingBottom() - marginBottom;
            final int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++){
                final View child = parent.getChildAt(i);

                //获得child的布局信息
                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)child.getLayoutParams();
                final int left = child.getRight() + params.rightMargin;
                final int right = left + mDividerWidth;
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }
    }
}
